package org.lanqiao.tjut.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lanqiao.tjut.bean.TBAdminBean;
import org.lanqiao.tjut.myUtils.MyUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserLoinedInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/*
		 * 拦截器的工作原理： 拦截器的处理方法如果返回： false --- 拦截 ture --- 不拦截
		 */
		/*
		 * 进行拦截器的业务逻辑处理：验证用户是否进行了登录 1、当前被拦截处理是登录处理流程，放行； 2、非登录处理流程
		 * 验证session中是否缓存了用户登录信息，根据验证结果决定是否需要进行拦截
		 */
		// 登录请求，放行
		// 静态资源请求，放行
		if (request.getRequestURI().contains("doAdminLoginAction")
				|| request.getRequestURI().contains("bootstrap-3.3.7-dist")
				|| request.getRequestURI().contains("jquery-1.12.4")
				|| request.getRequestURI().contains("loginedResource")
				|| request.getRequestURI().contains("loginResource")
				|| request.getRequestURI().contains("bootstrap-datetimepicker")
				|| request.getRequestURI().contains("pagination-2.0.7")
				|| request.getRequestURI().contains("uploadfiles")) {
			// 正在进行登录请求,放行
			return true;
		}

		// 非登录请求，验证session中是否有缓存信息
		TBAdminBean adminB = (TBAdminBean) request.getSession().getAttribute("LoginedAdminInfo");
		if (adminB != null && adminB.getAdmins_name() != null && !adminB.getAdmins_name().equals("")) {
			// 用户信息验证成功
			// 放行
			MyUtils.logger.info("拦截器--当前登录用户：" + adminB.getAdmins_name());
			return true;
		} else {
			// 用户验证失败，进行拦截
			// 跳转回登录页面
			// 转发
			// request.getRequestDispatcher("index").forward(request, response);
			// 重定向
			response.sendRedirect("../index.jsp");
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
